//
//  BVService.m
//  AFNetworking
//
//  Created by 崔晋 on 2019/8/11.
//

#import "BVService.h"
#import "AFNetworking.h"


static NSString * const HOST_URL = @"https://sandbox.zheshi.tech/v1";

@interface BVService ()
@property (nonatomic, strong) AFNetworkReachabilityManager *manager;
@property (nonatomic, assign) AFNetworkReachabilityStatus networkStatus;
@end

@implementation BVService


+ (void)load {
    [BVService shareInstance];
}

+ (instancetype)shareInstance {
    static BVService *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BVService alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _manager = [AFNetworkReachabilityManager  sharedManager];
        __weak typeof(self)weakSelf = self;
        [_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            weakSelf.networkStatus = status;
        }];
        [_manager startMonitoring];
    }
    return self;
}

- (NSURLSessionDataTask *)post:(NSString *)url requestBodt:(NSDictionary *)param complete:(void (^)(BOOL, id _Nullable))complete {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HOST_URL]];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:[BVUser shareInstance].token?:@"" forHTTPHeaderField:@"X-Elephant-Token"];
    NSLog(@"请求参数 ： \n%@", [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]);
    NSURLSessionDataTask *task = [manager POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject == nil) {
            if (complete) {
                complete(NO, nil);
            }
        }else {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSError *error;
                NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@", jsonStr);
                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
                if (error) {
                    if (complete) {
                        complete(NO, responseObject);
                    }
                    return;
                }
            }
            if (complete) {
                complete(YES, responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(NO, nil);
        }
    }];
    return task;
}

- (NSURLSessionDataTask *)get:(NSString *)url
                        param:(NSDictionary *)param
                     complete:(void (^)(BOOL, id _Nullable))complete {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HOST_URL]];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript", nil];
    [manager.requestSerializer setValue:[BVUser shareInstance].token?:@"" forHTTPHeaderField:@"X-Elephant-Token"];
    NSURLSessionDataTask *task = [manager GET:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject == nil) {
            if (complete) {
                complete(NO, nil);
            }
        }else {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSError *error;
                NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@", jsonStr);
                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
                if (error) {
                    if (complete) {
                        complete(NO, responseObject);
                    }
                    return;
                }
            }else {
                NSString *jsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
                NSLog(@"%@", jsonStr);
            }
            if (complete) {
                complete(YES, responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(NO, nil);
        }
    }];
    return task;
}

- (NSURLSessionDataTask *)put:(NSString *)url
                  requestBodt:(NSDictionary *)param
                     complete:(void (^)(BOOL, id _Nullable))complete {
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HOST_URL]];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:[BVUser shareInstance].token?:@"" forHTTPHeaderField:@"X-Elephant-Token"];
    NSLog(@"请求参数 ： \n%@", [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]);
    
    NSURLSessionDataTask *task = [manager PUT:url parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject == nil) {
            if (complete) {
                complete(NO, nil);
            }
        }else {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSError *error;
                NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@", jsonStr);
                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
                if (error) {
                    if (complete) {
                        complete(NO, responseObject);
                    }
                    return;
                }
            }
            if (complete) {
                complete(YES, responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(NO, nil);
        }
    }];
    return task;
}

- (NSURLSessionTask *)postImageWithUrl:(NSString *)url
                                 image:(UIImage *)image
                                   key:(NSString *)key
                              progress:(nonnull DownloadProgress)progress
                              complete:(void (^ _Nullable)(BOOL, id _Nonnull))complete {
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:HOST_URL]];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:[BVUser shareInstance].token?:@"" forHTTPHeaderField:@"X-Elephant-Token"];
    [manager POST:url parameters:@{key: @"image.png"} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        UIImage *pressImage = [UIImage imageWithData:imageData];
        UIImageWriteToSavedPhotosAlbum(pressImage, nil, nil, nil);
        [formData appendPartWithFileData:imageData
                                    name:[NSString stringWithFormat:@"%@", key]
                                fileName:@"image.png"
                                mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress?progress(uploadProgress):nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject == nil) {
            if (complete) {
                complete(NO, nil);
            }
        }else {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSError *error;
                NSString *jsonStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@", jsonStr);
                responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
                if (error) {
                    if (complete) {
                        complete(NO, responseObject);
                    }
                    return;
                }
            }
            if (complete) {
                complete(YES, responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (complete) {
            complete(NO, nil);
        }
    }];
    return nil;
}

- (NSURLSessionTask *)downloadVideoWithUrl:(NSString *)url progress:(nonnull DownloadProgress)progress complete:(void (^ _Nullable)(BOOL, id _Nullable))complete {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://obs.zheshi.tech/%@", url]]];
    NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, [url componentsSeparatedByString:@"/"].lastObject];
    NSURLSessionTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        if (progress) {
            progress(downloadProgress);
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            if (complete) {
                complete(NO, nil);
            }
        }else {
            if (complete) {
                complete(YES, filePath);
            }
        }
    }];
    [task resume];
    return task;
}

- (BOOL)isWifi {
    return self.networkStatus == AFNetworkReachabilityStatusReachableViaWiFi;
}

@end
